from django.shortcuts import render, redirect
from workDjango import models
from django.utils.safestring import mark_safe
from django import forms
from django.core.validators import RegexValidator, ValidationError


class AddModelForm(forms.ModelForm):
    # 由于使用了ModelForm组件，无法在html文件中设立样式
    # 在这里设置相关的样式
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环找到所有的插件，添加样式
        for name, field in self.fields.items():
            if field.widget.attrs:
                field.widget.attrs["class"] = "form-control"
                field.widget.attrs["placeholder"] = field.label
            else:
                field.widget.attrs = {"class": "form-control", "placeholder": field.label}

    # 验证数据是否存在
    def clean_mobile(self):
        # txt_mobile = self.cleaned_data["mobile"]
        # exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
        # if exists:
        #     raise ValidationError("手机号已存在")
        # return txt_mobile
        txt_shopname = self.cleaned_data["product_name"]
        exists = models.Product.objects.exclude(id=self.instance.pk).filter(product_name=txt_shopname).exists()
        #exists = models.echartsTest.objects.exclude(id=self.instance.pk).filter(shopname=txt_shopname).exists()
        if exists:
            raise ValidationError("商品类别已存在")
        return txt_shopname


class EditModelForm(forms.ModelForm):
    # 由于使用了ModelForm组件，无法在html文件中设立样式
    # 在这里设置相关的样式
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环找到所有的插件，添加样式
        for name, field in self.fields.items():
            if field.widget.attrs:
                field.widget.attrs["class"] = "form-control"
                field.widget.attrs["placeholder"] = field.label
            else:
                field.widget.attrs = {"class": "form-control", "placeholder": field.label}


class FindModelForm(forms.ModelForm):
    # 由于使用了ModelForm组件，无法在html文件中设立样式
    # 在这里设置相关的样式
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环找到所有的插件，添加样式
        for name, field in self.fields.items():
            if field.widget.attrs:
                field.widget.attrs["class"] = "form-control"
                field.widget.attrs["placeholder"] = field.label
            else:
                field.widget.attrs = {"class": "form-control", "placeholder": field.label}


class ManagerModelForm(forms.ModelForm):
    # 由于使用了ModelForm组件，无法在html文件中设立样式
    # 在这里设置相关的样式
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环找到所有的插件，添加样式
        for name, field in self.fields.items():
            if field.widget.attrs:
                field.widget.attrs["class"] = "form-control"
                field.widget.attrs["placeholder"] = field.label
            else:
                field.widget.attrs = {"class": "form-control", "placeholder": field.label}
